<?php
abstract class RCMSDaoBase {
	protected $con;

	public function beginTransaction() {
		$this->con->beginTransaction();
	}
	public function commit() {
		$this->con->commit();
	}
	public function rollBack() {
		$this->con->rollBack();
	}	
	public function __construct($con) {
		$this->setConnection($con);
	}

	public function setConnection($con){
		$this->con = $con;
	}

	public function execute($sql, $params = array()){
		$stmt = $this->con->prepare($sql);
		$stmt->execute($params);
		return $stmt;
	}

	public function fetch($sql, $params = array()) {
		return $this->execute($sql, $params)->fetch(PDO::FETCH_ASSOC);
	}

	public function fetchAll($sql, $params = array()){
		return $this->execute($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
	}

	public function makeInsertSql($tableName, $columns) {
		$sql = 'INSERT INTO ' + $tableName +  '(' + $this->makeColumnList($columns, true) +  ') VALUES(' + $this->makeColumnList($columns, false) + ')';
		return $sql;
	}
	public function makeSelectSql($tableName, $columns, $whereClause, $orderClause) {
		$sql ='SELECT '.$this->makeColumnList($columns, true).' FROM '.$tableName
		.' '.$this->makeSqlWhereClause($whereClause).' '.$this->makeSqlOrderClause($orderClause);
		//var_dump($sql);
		return $sql;
	}
	public function makeUpdateSql($tableName, $columns, $whereClause) {
		$sql = 'UPDATE '.$tableName.' SET '.join(', ', $columns).' '.$this->makeSqlWhereClause($whereClause);
		//var_dump($sql);
		return $sql;
	}

	protected function makeColumnList($columns, $bNameOrValue) {
		if ($bNameOrValue) {
			return ' '.join(', ', $columns);
		} else {
			return ' '.join(', :', $columns);
		}
	}
	protected function makeSqlWhereClause($clause) {
		if (is_null($clause) || sizeof($clause)==0 ) return '';
		return ' WHERE ' . join(' AND ', $clause);
	}
	protected function makeSqlOrderClause($clause) {
		if (is_null($clause) || sizeof($clause)==0 ) return '';
		return ' ORDER BY ' . join(', ', $clause);
	}
}
?>
